from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView

from django_redis import get_redis_connection
from django import http
from celery_tasks.sms.tasks import send_sms_code
import random,logging

from register.serializers import CreateUserSerializer
# Create your views here.

#创建日志输出器
logger = logging.getLogger('django')
#发动短信验证码
class SmsView(APIView):
    def get(self,request,mobile):
        sms_code = '%06d' % random.randint(0,999999)
        logger.info(sms_code)
        #创建redis连接对象
        redis_conn = get_redis_connection('verify_code')
        #创建管道
        pipe = redis_conn.pipeline()
        #保存短信验证码到redis
        pipe.setex(f'sms_{mobile}',300,sms_code)
        #保存改手机号码的标记，防止频繁发送短信
        pipe.setex(f'send_flag_{mobile}',60,1)
        #执行管道
        pipe.execute()
        #使用celery异步发送短信
        send_sms_code.delay(mobile,sms_code)
        #返回响应
        return Response({'success': True, 'sms_code': sms_code, 'message': 'OK'})


#用户注册
class CreateUserView(CreateAPIView):
    serializer_class = CreateUserSerializer